﻿using JZ_UDI.DataAccess;
using JZ_UDI.DataAccess.DataEntity;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Linq;
using System.Windows.Forms;

namespace JZ_UDI.View.Settings
{
    public partial class frmAccountManagement : Form
    {
        public frmAccountManagement()
        {
            InitializeComponent();
        }

        List<UserPrivilege> userPrivileges;
        User user;
        EFDbContext context = new EFDbContext();

        private void frmAccountManagement_Load(object sender, EventArgs e)
        {
            //获得所有帐号
            List<User> users = context.Users.ToList();
            dgvUsers.AutoGenerateColumns = false;
            dgvUsers.DataSource = users;
            dgvUsers.Columns[0].DataPropertyName = "UserName";

            //获得所有权限列表
            List<PrivilegeList> privilegeLists = context.privilegeLists.ToList();
            var priClassKeys = privilegeLists.GroupBy(item => item.PrivilegeClass);
            foreach (var group in priClassKeys)
            {
                TreeNode treeNode = new TreeNode(group.Key.ToString());
                treeView1.Nodes.Add(treeNode);
                foreach (var item in group)
                {
                    treeNode.Nodes.Add(item.ID.ToString(), item.PrivilegeItem);
                }
            }
            userPrivileges = context.UserPrivileges.ToList();


            treeView1.ExpandAll();
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (dgvUsers.SelectedRows.Count <= 0)
            {
                MessageBox.Show("请先选择帐号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            user = dgvUsers.SelectedRows[0].DataBoundItem as User;

            if (e.Node != null)
            {
                if (e.Node.Parent == null)// 这是根节点 
                {
                    //如果为选中状态，则取消选中，并清除权限
                    //如果为非选中状态，则先选中，并添加权限
                    TraverseTreeNodes(e.Node, e.Node.Checked);
                }
                else// 这是子节点  
                {
                    TraverseTreeChildNodes(e.Node, e.Node.Checked);
                }



            }

        }


        private void TraverseTreeNodes(TreeNode nodes, bool selected)
        {
            foreach (TreeNode node in nodes.Nodes)
            {
                // 处理当前节点
                if (!selected)
                {
                    node.Checked = false;
                    string sql = "delete UserPrivilege where UserID=@uid and PrivilegeID=@pid";
                    var parameters = new SqlParameter[]
                    {
                            new SqlParameter("@uid", user.ID),
                            new SqlParameter("@pid",node.Name)
                    };
                    context.Database.ExecuteSqlCommand(sql, parameters);

                }
                else
                {
                    
                    node.Checked = true;

                    string sql = "select * from UserPrivilege where UserID=@uid and PrivilegeID=@pid";

                    var parameters = new SqlParameter[]
                    {
                            new SqlParameter("@uid", user.ID),
                            new SqlParameter("@pid",node.Name)
                    };
                    DbRawSqlQuery<UserPrivilege> count =context.Database.SqlQuery<UserPrivilege>(sql, parameters);
                    if (count.ToList().Count() <= 0)
                    {
                        sql = "insert into UserPrivilege(UserID,PrivilegeID) values (@uid,@pid)";
                        var parameters2 = new SqlParameter[]
                    {
                            new SqlParameter("@uid", user.ID),
                            new SqlParameter("@pid",node.Name)
                    };
                        context.Database.ExecuteSqlCommand(sql, parameters2);
                    }

                }
            }
        }

        private void TraverseTreeChildNodes(TreeNode nodes, bool selected)
        {

            // 处理当前节点
            if (!selected)
            {
                nodes.Checked = false;
                string sql = "delete UserPrivilege where UserID=@uid and PrivilegeID=@pid";
                var parameters = new SqlParameter[]
                {
                            new SqlParameter("@uid", user.ID),
                            new SqlParameter("@pid", nodes.Name)
                };
                context.Database.ExecuteSqlCommand(sql, parameters);
            }
            else
            {
                nodes.Checked = true;
                string sql = "select * from UserPrivilege where UserID=@uid and PrivilegeID=@pid";

                var parameters = new SqlParameter[]
                {
                            new SqlParameter("@uid", user.ID),
                            new SqlParameter("@pid",nodes.Name)
                };
                DbRawSqlQuery<UserPrivilege> count = context.Database.SqlQuery<UserPrivilege>(sql, parameters);
                if (count.ToList().Count() <= 0)
                {
                    sql = "insert into UserPrivilege(UserID,PrivilegeID) values (@uid,@pid)";
                    var parameters2 = new SqlParameter[]
                {
                            new SqlParameter("@uid", user.ID),
                            new SqlParameter("@pid",nodes.Name)
                };
                    context.Database.ExecuteSqlCommand(sql, parameters2);
                }
            }

        }

        private void dgvUsers_Click(object sender, EventArgs e)
        {
            

            if (dgvUsers.SelectedRows.Count <= 0)
            {
                return;
            }
             user = (User)dgvUsers.SelectedRows[0].DataBoundItem;

            string sql = "select * from UserPrivilege where UserID=@uid";
            var parameters = new SqlParameter[]
                {
                            new SqlParameter("@uid", user.ID)
                };

            DbRawSqlQuery<UserPrivilege> ups= context.Database.SqlQuery<UserPrivilege>(sql, parameters);

            TreeNodeCollection tnc = treeView1.Nodes;

            foreach (UserPrivilege up in ups)
            {
                foreach (TreeNode tn in tnc)
                {
                    if (tn.Parent == null)
                    {
                        foreach (TreeNode tn2 in tn.Nodes)
                        {
                            if (tn2.Name.Equals(up.PrivilegeID.ToString()))
                            {
                                // treeView1.Nodes[up.PrivilegeID.ToString()].Checked = true;
                                tn2.Checked = true;
                            }
                            
                        }
                    }
                }
            }

        }

        private void btnAddUser_Click(object sender, EventArgs e)
        {
            frmAddUser frmAddUser = new frmAddUser();
            frmAddUser.addFormClose += FrmAddUser_addFormClose;
            frmAddUser.ShowDialog();
        }

        private void FrmAddUser_addFormClose(object sender, string username)
        {
            frmAccountManagement_Load(null,null);
        }
    }
}
